/*********************************************************************************
 *      Copyright:  (C) 2023 iot<iot@email.com>
 *                  All rights reserved.
 *
 *       Filename:  get_data.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/20/23)
 *         Author:  iot <iot@email.com>
 *      ChangeLog:  1, Release initial version on "04/20/23 18:46:22"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stddef.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>
#include<fcntl.h>
#include <unistd.h>
#include<sys/time.h>

#include "get_data.h"

int get_devid(char *devid,int size)
{
    char *dev = "whj1";
    
    if( !devid || size<=0 )
    {
        printf("invalid input arguments\n");
        return -1;
    }

    memcpy(devid,dev,strlen(dev)+1);
    return 0;
}

int get_time(char *time_now,int size)
{
    long                    s;
    struct timeval           tv;
    struct tm*              st;

	if( !time_now || size<=0 )
	{
		printf("invalid input arguments\n");
		return -1;
	}

    gettimeofday(&tv, NULL);
	s = tv.tv_sec;
	st = localtime(&tv.tv_sec);
	
	memset(time_now, 0, sizeof(time_now));
    
	snprintf(time_now, 100,"%04d-%02d-%02d--%02d:%02d:%02d", st->tm_year+1900, st->tm_mon+1, st->tm_mday, st->tm_hour, st->tm_min, st->tm_sec);
     
	return s;
}

int ds18b20_get_temperature(float *temp)
{
    char                dev_path[128] = "/sys/bus/w1/devices/";
    DIR                 *dirp = NULL;
    struct dirent       *direntp = NULL;
    char                chip[32];
    int                 found = 0;
    char                buf[128];
    char                *ptr = NULL;
    int                 fd = -1;

    if( !temp )
    {
        return -1;
    }

    if((dirp = opendir(dev_path)) == NULL)
    {
        printf("opendir error:%s\n",strerror(errno));
        return -2;
    }

    while((direntp=readdir(dirp)) != NULL)
    {
        if(strstr(direntp->d_name,"28-"))
        {
            strncpy(chip,direntp->d_name,sizeof(chip));
            found = 1;
        }
    }
    closedir(dirp);


	if( !found )

    {
        printf("can not find ds18b20 in %s\n",dev_path);
        return -3;
    }

	strncat(dev_path,chip,sizeof(dev_path)-strlen(dev_path));
    strncat(dev_path,"/w1_slave",sizeof(dev_path)-strlen(dev_path));

    if( (fd=open(dev_path,O_RDONLY))<0 )
    {
        printf("open %s error: %s\n", dev_path, strerror(errno));
        return -4;
    }

    if(read(fd,buf,sizeof(buf))<0)
    {
        printf("read %s error: %s\n", dev_path, strerror(errno));
        return -5;
    }

    ptr = strstr(buf,"t=")+2;

    if( !ptr )
    {
        printf("ERROR: Can not get temperature\n");
        return -6;
    }

    *temp = atof(ptr)/1000;

    return 0;

}



